package com.jy.appmarket.fragment;

import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.view.CardListView;
import it.gmariotti.cardslib.library.view.PullToRefreshListView.RefreshingListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.jy.app.market.idata.card.CardUpgrade;
import com.jy.app.market.idata.data.Upgrade;
import com.jy.appmarket.R;
import com.jy.appmarket.cards.BaseUICard;
import com.jy.appmarket.cards.CardsUtils;
import com.jy.appmarket.cards.DownloadableUICard;
import com.jy.appmarket.cards.UpgradeUICard;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.download.DownloadService;
import com.jy.appmarket.download.DownloadUtils;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.DiscoveryNetEngine;
import com.jy.appmarket.network.engine.cachestrategy.CacheStrategy;
import com.jy.appmarket.network.resultdata.PageResult;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;
import com.jy.appmarket.service.UpdateService;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.PackageUtils;
import com.jy.appmarket.utils.Prefs;
import com.jy.appmarket.view.LoadingView;
import com.jy.appmarket.view.LoadingView.OnClickListener;

public class FragmentDiscovery extends Fragment implements NetTaskListener, OnClickListener, RefreshingListener {
	private static final String TAG = "FragmentDiscovery";

	private DownloadActivity mActivity;
	private boolean mIsCreated = false;

	private CardListView mListview;
	private CardArrayAdapter mCardsAdapter;
	private ArrayList<Card> mCardsArray = new ArrayList<Card>();
	private NetTask mNetTask;

	private LoadingView mLoadingView;
	private int mPageIndex = 1;
	private boolean mIsFooterRefresh = false;
	private long mDataVersion;

	private UpgradeUICard mUpgradeUICard;

	private UpgradeCardReceiver mUpgradeCardReceiver = new UpgradeCardReceiver();

	@Override
	public void onAttach(Activity activity) {
		mActivity = (DownloadActivity) activity;
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.discovery_fragment_layout, container, false);
		initLoadingView(view);
		initListView(view);
		loadData(true);
		registerBroadcastReceiver();

		return view;
	}

	private void loadData(boolean loadFirstPage) {
		int pageIndex = mPageIndex;
		if (loadFirstPage) {
			pageIndex = 1;
			mDataVersion = 0;
			mLoadingView.showWaitView(R.string.ptr1_loading_wait);

			mListview.setVisibility(View.GONE);
			mLoadingView.setVisibility(View.VISIBLE);
		}
		DiscoveryNetEngine engine = new DiscoveryNetEngine(mDataVersion, pageIndex);
		engine.setCacheStrategy(new CacheStrategy(true, CacheStrategy.THREE_HOUR));
		mNetTask = new NetTask(mActivity, engine, 1);
		mNetTask.setListener(this);
		new Thread(mNetTask).start();
	}

	private void initListView(View v) {
		mListview = v.findViewById(R.id.discovery_fragment_cardlist);
		mListview.setEmptyView(mLoadingView);
		mListview.needToRefreshOnFooter(true);
		mListview.needToRefreshOnHeader(false);
		mListview.setRefreshListener(this);
		mListview.setVisibility(View.GONE);

		mCardsAdapter = new CardArrayAdapter(mActivity, mCardsArray);
		mCardsAdapter.setInnerViewTypeCount(100);
		mListview.setAdapter(mCardsAdapter);
	}

	private void initLoadingView(View v) {
		mLoadingView = v.findViewById(R.id.loading_view_layout);
		mLoadingView.setOnClickListener(this);
		mLoadingView.showWaitView(mActivity.getString(R.string.loading_wait));
	}

	private void registerBroadcastReceiver() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(UpdateService.ACTION_SHOW_UPGRADE_CARD);
		getActivity().registerReceiver(mUpgradeCardReceiver, filter);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mIsCreated = true;
	}

	@Override
	public void onDestroy() {

		if (mNetTask != null) {
			mNetTask.cancel();
			mNetTask.setListener(null);
			mNetTask = null;
		}
		if (mUpgradeCardReceiver != null) {
			getActivity().unregisterReceiver(mUpgradeCardReceiver);
			mUpgradeCardReceiver = null;
		}
		super.onDestroy();
	}

	private boolean needShowUpgradeCard(Upgrade upgrade) {
		if (upgrade.getVersionCode() <= PackageUtils.getVersionCode(mActivity)) {
			return false;
		}
		if (TextUtils.isEmpty(upgrade.getUrl())) {
			return false;
		}
		String dlId = DownloadUtils.generateDownloadId(mActivity.getPackageName(), upgrade.getVersionCode());
		int status = mActivity.getDownloadStatus(dlId, mActivity.getPackageName(), upgrade.getVersionCode());
		if (status != DownloadService.STATUS_NO_STATUS && status != DownloadService.STATUS_CAN_INSTALL) {
			return false;
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
		String currentDate = dateFormat.format(System.currentTimeMillis());
		String previousDate = Prefs.getUpgradeCardDate(mActivity);
        return !currentDate.equals(previousDate);
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (!mIsCreated) {
			return;
		}
		if (isVisibleToUser) {
			Log.d(TAG, "emulate onResume");
		} else {
			Log.d(TAG, "emulate onPaused");
		}
	}

	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		PageResult resultData = (PageResult) engine.getResultData();
		if (!resultData.isOK()) {
			if (mPageIndex == 1) {
				mLoadingView.showErrorView(R.string.load_failed_retry);
			}
		} else {
			List<com.jy.app.market.idata.card.Card> cards = resultData.getCards();
			if (cards == null || cards.size() == 0) {
				if (mLoadingView.getVisibility() == View.VISIBLE) {
					mLoadingView.showErrorView(R.string.no_data);
					return;
				}
			} else {
				mDataVersion = resultData.getDataVersion();
				for (com.jy.app.market.idata.card.Card card : cards) {
					BaseUICard uiCard = CardsUtils.getCardInstance(mActivity, card);
					if (uiCard == null) {
						LogUtil.w(TAG, "Unsupport " + card.getType() + " at " + mCardsArray.size());
						continue;
					}

					uiCard.setIndex(mCardsArray.size());
					if (uiCard instanceof DownloadableUICard) {
						DownloadableUICard c = (DownloadableUICard) uiCard;
						c.setListView(mListview);
						mActivity.addFileListener(c);
					}
					uiCard.setApkSource(new ApkSource("discovery", uiCard.getIndex(), mDataVersion));

					if (uiCard instanceof UpgradeUICard) {
						UpgradeUICard uc = (UpgradeUICard) uiCard;
						Upgrade u = getUpgrade(mActivity);
						if (needShowUpgradeCard(u)) {
							uc.setUpgrade(u);
							uc.setParentAdapter(mCardsAdapter);
						} else {
							mUpgradeUICard = uc;
							continue;
						}
					}
					mCardsArray.add(uiCard);
				}
				mCardsAdapter.notifyDataSetChanged();
				mListview.footerRefreshingCompleted();
				mListview.setVisibility(View.VISIBLE);
				mLoadingView.setVisibility(View.GONE);
				mPageIndex++;
				if (mIsFooterRefresh) {
					mIsFooterRefresh = false;
				}

				if (resultData.getPageNo() >= resultData.getTotalPage()) {
					mListview.needToRefreshOnFooter(false);
				}
			}
		}
	}

	@Override
	public void onTaskRunError(int tag) {
		if (mCardsAdapter.isEmpty()) {
			mListview.setVisibility(View.GONE);
			mLoadingView.showErrorView(mActivity.getString(R.string.ptrl_refresh_fail));
		} else {
			if (mIsFooterRefresh) {
				mListview.footerRefreshError();
				mIsFooterRefresh = false;
			}
		}
		Toast.makeText(mActivity, R.string.network_error, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onTaskRunCanceled(int tag) {

	}

	@Override
	public void onLoadingViewClick(View view) {
		loadData(true);
	}

	@Override
	public void onHeaderRefreshing() {
		// nothing todo
	}

	@Override
	public void onFooterRefreshing() {
		mIsFooterRefresh = true;
		loadData(false);
		// LogUtil.d(TAG, "onFooterRefreshing");
	}

	private Upgrade getUpgrade(Context context) {
		Upgrade upgrade = new Upgrade();
		upgrade.setVersionCode(Prefs.getUpgradeVersionCode(context));
		upgrade.setIcon(Prefs.getUpgradeIcon(context));
		upgrade.setTitle(Prefs.getUpgradeTitle(context));
		upgrade.setDetail(Prefs.getUpgradeDetail(context));
		upgrade.setUrl(Prefs.getUpgradeUrl(context));
		upgrade.setIndex(Prefs.getUpgradeIndex(context));
		return upgrade;
	}

	private class UpgradeCardReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent == null) {
				return;
			}
			if (UpdateService.ACTION_SHOW_UPGRADE_CARD.equals(intent.getAction())) {
				if (mCardsArray == null || mCardsArray.size() == 0) {
					return;
				}
				// 遍历list，如果有upgrade卡片则退出
				for (Card card : mCardsArray) {
					if (card instanceof UpgradeUICard) {
						return;
					}
				}
				CardUpgrade cardUpgrade = (CardUpgrade) intent.getSerializableExtra(UpdateService.EXTRA_UPGRADE_INFO);
				if (cardUpgrade == null) {
					return;
				}
				Upgrade upgrade = cardUpgrade.getUpgrade();
				if (upgrade == null) {
					return;
				}
				if (!needShowUpgradeCard(upgrade)) {
					return;
				}
				if (mUpgradeUICard == null) {
					mUpgradeUICard = new UpgradeUICard(context, cardUpgrade);
					mUpgradeUICard.setIndex(0);
				} else {
					mUpgradeUICard.setUpgrade(upgrade);
				}
				mUpgradeUICard.setParentAdapter(mCardsAdapter);
				mCardsArray.add(mUpgradeUICard.getIndex(), mUpgradeUICard);
				mCardsAdapter.notifyDataSetChanged();
			}
		}

	}
}